<?php

namespace app\api\model;

use fast\Http;
use think\Model;
use think\Request;

Class Sign extends Model {


    public function __construct($merchant_id = '', $key = '') {
        $this->domain  = Request::instance()->domain();
    }

    public function check($params)
    {

        $order = Db('orderLists')->where(['ordersn' => $params['ordersn']])->find();
        if (!$order){
            return  false;
        }
        $key = Db('platformLists')->where('enname','=',$order['platform'])->value('key');

        $data = array(
            'ordersn'   => $order['ordersn'],
            'price' => $order['price'],
            'callbackurl'   => $order['callbackurl'],
            'nonce_str' => $params['nonce_str'],
            'RefundOrderNo' => $params['RefundOrderNo'],

        );

        $hmacVal = urlencode($this->hmacRequest($data,$key));

        if ($params['hmac'] != $hmacVal) {
            return false;
        }

        return true;
    }

    protected function hmacRequest($params, $key, $encryptType = "1")
    {
        if ("1" == $encryptType) {
            return md5(implode("", $params) . $key);
        } else {
            $private_key = openssl_pkey_get_private($key);
            $params = implode("", $params);
            openssl_sign($params, $sign, $private_key, OPENSSL_ALGO_MD5);
            openssl_free_key($private_key);
            $sign = base64_encode($sign);
            return $sign;
        }
    }

}

